package flex.cc.drive.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;

import flex.cc.PublicUtil;
import flex.cc.common.utils.HttpClientUtil;
import flex.cc.drive.dao.DriverInterfaceLogDao;
import flex.cc.drive.dto.DriverInterfaceLogEntity;
import flex.cc.drive.service.CheckScopeService;
import flex.cc.drive.util.DriveDESUtil;
import flex.cc.store.dao.StoreCouponDao;
import flex.cc.store.dto.entity.StoreCouponEntity;
import flex.cc.util.APIConfigUtil;

/**
*
* @author R
* 2022年01月14日 13:35:01
* @desc 电子围栏校验实现层
*/
@Service("checkScopeService")
@Transactional(rollbackFor = Exception.class)
public class CheckScopeServiceImpl implements CheckScopeService {
    private static final Logger logger = LoggerFactory.getLogger(CheckScopeServiceImpl.class);

//    @Value("${api.config.checkScopeUrl}")
//    private String checkScopeUrl;
//    @Value("${api.config.key}")
//    private String key;
//    @Value("${redeemcode.source}")
//    private String source;
    @Autowired
    private DriverInterfaceLogDao driverInterfaceLogDao;
    @Autowired
    private StoreCouponDao storeCouponDao;
    @Autowired
	private APIConfigUtil apiConfigUtil;
    
	@Override
	public JSONObject checkScope(Map<String, Object> requestBodyMap) {
		JSONObject jsonResult = new JSONObject();
		Map<String, Object> dataMap = new HashMap<String, Object>();
		Map<String, Object> requestMap = new HashMap<String, Object>();
		try {
			//预约地省份
			String province = (String) requestBodyMap.get("province");
			if(PublicUtil.isEmpty(province)) {
	    		logger.error("预约地省份不能为空");
	    		jsonResult.put("resultCode", "01");
	    		jsonResult.put("resultDesc", "预约地省份不能为空");
	            return jsonResult;
			}
			dataMap.put("province", province);
			//预约地市
			String city = (String) requestBodyMap.get("city");
			if(PublicUtil.isEmpty(city)) {
	    		logger.error("预约地市不能为空");
	    		jsonResult.put("resultCode", "01");
	    		jsonResult.put("resultDesc", "预约地市不能为空");
	            return jsonResult;
			}
			dataMap.put("city", city);
			//预约区域
			String county = (String) requestBodyMap.get("county");
			if(PublicUtil.isEmpty(county)) {
	    		logger.error("预约区域不能为空");
	    		jsonResult.put("resultCode", "01");
	    		jsonResult.put("resultDesc", "预约区域不能为空");
	            return jsonResult;
			}
			dataMap.put("county", county);
			//地图类型
			String fenceType = (String) requestBodyMap.get("fenceType");
			if(PublicUtil.isEmpty(fenceType)) {
	    		logger.error("地图类型不能为空");
	    		jsonResult.put("resultCode", "01");
	    		jsonResult.put("resultDesc", "地图类型不能为空");
	            return jsonResult;
			}
			dataMap.put("fenceType", fenceType);
			//维度坐标
			String latitude = (String) requestBodyMap.get("latitude");
			if(PublicUtil.isEmpty(latitude)) {
	    		logger.error("维度坐标不能为空");
	    		jsonResult.put("resultCode", "01");
	    		jsonResult.put("resultDesc", "维度坐标不能为空");
	            return jsonResult;
			}
			dataMap.put("latitude", latitude);
			//经度坐标
			String longitude = (String) requestBodyMap.get("longitude");
			if(PublicUtil.isEmpty(longitude)) {
	    		logger.error("经度坐标不能为空");
	    		jsonResult.put("resultCode", "01");
	    		jsonResult.put("resultDesc", "经度坐标不能为空");
	            return jsonResult;
			}
			dataMap.put("longitude", longitude);
			//服务项目
			String activityId = (String) requestBodyMap.get("activityId");
			if(PublicUtil.isEmpty(activityId)) {
	    		logger.error("服务项目不能为空");
	    		jsonResult.put("resultCode", "01");
	    		jsonResult.put("resultDesc", "服务项目不能为空");
	            return jsonResult;
			}
			dataMap.put("activityId", activityId);
			
			String couponNum = (String)requestBodyMap.get("couponNum");
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("couponNum", couponNum);
			StoreCouponEntity couponEntity = storeCouponDao.getOneByParams(params);
			String provider = couponEntity.getServer();
			String source = apiConfigUtil.getApiConfig(provider, "disponse_code");
			dataMap.put("source", source);
			
			JSONObject dateJsonObj=new JSONObject(dataMap);
			logger.info(new Date() + "==" + dataMap.toString());
			
			String key = apiConfigUtil.getApiConfig(provider, "drive_decode");
			String key3Des = apiConfigUtil.getApiConfig(provider, "store_key3Des");
			String encryptDateStr = DriveDESUtil.driverEncrypt(dateJsonObj.toString(), key,key3Des);
			requestMap.put("source", source);
			requestMap.put("data", encryptDateStr);
			JSONObject requestJsonObj=new JSONObject(requestMap);
			
			Date requestDate = new Date();
	        // 调用电子围栏校验接口
			String checkScopeUrl = apiConfigUtil.getApiConfig(provider, "drive_checkScope");
			logger.info("调用电子围栏校验接口url ==" + checkScopeUrl);
			logger.info("调用电子围栏校验接口请求报文 ==" + requestJsonObj.toString());
	    	String packageResult = HttpClientUtil.sendHttpPost(checkScopeUrl, requestJsonObj.toString(), new HashMap<String, String>(){{
	            put("Content-Type", "application/json;charset=UTF-8");
	        }});   
	    	Date responseDate = new Date();
	    	JSONObject resultObject = JSONObject.parseObject(packageResult);
	    	String dataId = UUID.randomUUID().toString().replace("-", "");
	    	DriverInterfaceLogEntity driverInterfaceLogEntity = new DriverInterfaceLogEntity();
	    	driverInterfaceLogEntity.setDataId(dataId);
	    	driverInterfaceLogEntity.setOrderId((String)requestBodyMap.get("couponNum"));
	    	driverInterfaceLogEntity.setInterfaceName("服务范围校验接口");
	    	driverInterfaceLogEntity.setRequestTime(requestDate);
	    	driverInterfaceLogEntity.setRequestBody(requestJsonObj.toString());
	    	driverInterfaceLogEntity.setResponseBody(packageResult);
	    	driverInterfaceLogEntity.setResponseTime(responseDate);
	    	driverInterfaceLogEntity.setCreateTime(new Date());
	    	driverInterfaceLogDao.insert(driverInterfaceLogEntity);
	    	
	        return resultObject;        
		} catch (Exception e) {
			logger.info("请求服务范围接口异常"+e.getMessage());
			jsonResult.put("resultCode", "01");
    		jsonResult.put("resultDesc", "请求服务范围接口异常");
            return jsonResult;
		}
    }
    
}
